package com.kaiwukj.android.ufamily.mvp.ui.page.service.complain;

import android.app.Activity;
import android.media.MediaPlayer;
import android.text.TextUtils;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.arouter.launcher.ARouter;
import com.blankj.utilcode.util.StringUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.kaiwukj.android.ufamily.R;
import com.kaiwukj.android.ufamily.app.constant.ARouterUrlKt;
import com.kaiwukj.android.ufamily.mvp.http.entity.result.ComplainResult;
import com.kaiwukj.android.ufamily.mvp.http.entity.resultbak.ComplainType;
import com.kaiwukj.android.ufamily.mvp.ui.adapter.UploadAdapter;
import com.kaiwukj.android.ufamily.mvp.ui.widget.home.PopupWindowUtil;
import com.kaiwukj.android.ufamily.utils.AudioUtils;
import com.kaiwukj.android.ufamily.utils.FormatUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import io.reactivex.Observable;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

import static com.kaiwukj.android.ufamily.mvp.ui.adapter.UploadAdapter.SHOWTYPE;
import static com.kaiwukj.android.ufamily.utils.Utils.runOnUiThread;

/**
 * @author Charles
 * @date 2019/8/16.
 * description：Kaiwu
 */
public class ComplainListAdapter extends BaseQuickAdapter<ComplainResult, BaseViewHolder> {
    private Activity activity;
    private UploadAdapter uploadAdapter;
    private MediaPlayer mediaPlayer;
    private Timer recordTimer;

    public ComplainListAdapter() {
        super(R.layout.item_complain_record, new ArrayList<>());
    }

    public void setActivity(Activity activity) {
        this.activity = activity;
    }

    @Override
    protected void convert(BaseViewHolder helper, ComplainResult item) {
        TextView tvTitle = helper.getView(R.id.tv_title);
        TextView tvTime = helper.getView(R.id.tv_time);
        TextView tvContent = helper.getView(R.id.tv_content);
        TextView tvReply = helper.getView(R.id.tv_reply_content);
        TextView tvRecord = helper.getView(R.id.tv_record);
        LinearLayout llReply = helper.getView(R.id.ll_reply);
        RecyclerView rvUpload = helper.getView(R.id.rv_complain_upload);

//        1:清洁卫生 2：保安 3：电梯 4：设施设备 5：绿化 6：房屋质量 7：物业管理人员 8：电梯 9：其他
        List<ComplainType> data = new ArrayList<>();
        data.add(new ComplainType(1, "清洁卫生"));
        data.add(new ComplainType(2, "保安"));
        data.add(new ComplainType(3, "电梯"));
        data.add(new ComplainType(4, "设施设备"));
        data.add(new ComplainType(5, "绿化"));
        data.add(new ComplainType(6, "房屋质量"));
        data.add(new ComplainType(7, "物业管理人员"));
        data.add(new ComplainType(8, "电梯"));
        data.add(new ComplainType(9, "其他"));
        for (ComplainType complainType : data) {
            if (item.getType() == complainType.getId()) {
                tvTitle.setText(complainType.getTypeName());
                break;
            }
        }
//        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        tvTime.setText(FormatUtils.formatTime(item.getComplainTime()));
        tvContent.setText(item.getContent());
        llReply.setVisibility(TextUtils.isEmpty(item.getContentReply()) ? View.GONE : View.VISIBLE);
        tvReply.setText(item.getContentReply());
        tvRecord.setVisibility(TextUtils.isEmpty(item.getVoice()) ? View.GONE : View.VISIBLE);
        if (!StringUtils.isEmpty(item.getVoice())) {
            Observable.create((ObservableOnSubscribe<Integer>) emitter ->
                    emitter.onNext(AudioUtils.getNetAudioTime(item.getVoice())))
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Observer<Integer>() {
                        @Override
                        public void onSubscribe(Disposable d) {

                        }

                        @Override
                        public void onNext(Integer integer) {
                            tvRecord.setVisibility(View.VISIBLE);
                            tvRecord.setText(String.format("%s\"", integer));
                        }

                        @Override
                        public void onError(Throwable e) {
                            if (e instanceof IOException) {
                                tvRecord.setVisibility(View.GONE);
                            }
                        }

                        @Override
                        public void onComplete() {

                        }
                    });
            tvRecord.getBackground().setLevel(2);
            recordTimer = new Timer();
            tvRecord.setOnClickListener(view -> {
                if (mediaPlayer == null) {
                    initPlayer(item.getVoice(), tvRecord);
                } else {
                    if (mediaPlayer.isPlaying()) {
                        mediaPlayer.stop();
                        mediaPlayer = null;
                    } else {
                        initPlayer(item.getVoice(), tvRecord);
                    }
                }
            });
        }

        uploadAdapter = new UploadAdapter(getContext(), SHOWTYPE);
        rvUpload.setLayoutManager(new GridLayoutManager(getContext(), 4));
        if (!TextUtils.isEmpty(item.getImg())) {
            List<String> imgs = Arrays.asList(item.getImg().split(","));
            uploadAdapter.setData(imgs);
        } else {
            List<String> imgs = new ArrayList<>();
            uploadAdapter.setData(imgs);
        }
        uploadAdapter.setVideoUrl(item.getCoverUrl());
        uploadAdapter.setHaveAudio(true);
        rvUpload.setAdapter(uploadAdapter);
        uploadAdapter.setOnItemClickListener(new UploadAdapter.onItemClickListener() {
            @Override
            public void onAudioClick() {

            }

            @Override
            public void onVideoClick() {

            }

            @Override
            public void onShowVideoClick(String coverUrl) {
                /*PopupWindowUtil.createVideoPop(activity, item.getVideo(), item.getCoverUrl())
                        .showCenter(R.layout.fragment_complain_list);*/
                ARouter.getInstance().build(ARouterUrlKt.VideoPlay)
                        .withString("videoUrl", item.getVideo())
                        .withString("coverUrl", item.getCoverUrl())
                        .withString("title", item.getContent())
                        .navigation(getContext());
            }

            @Override
            public void onDeleteVideoClick() {

            }

            @Override
            public void onAddClick() {

            }

            @Override
            public void onDelImgClick(int position) {

            }

            @Override
            public void onImgClick(List<String> imgUrls, int position) {
                PopupWindowUtil.createImageDialog(activity, imgUrls.get(position)).showCenter(R.layout.fragment_complain_list);
            }
        });
    }

    //    播放录音
    private void initPlayer(String filePath, TextView textView) {
//        关闭上一个播放的录音
        if (recordTimer != null) {
            recordTimer.cancel();
        }
        if (mediaPlayer != null) {
            mediaPlayer.stop();
        }
//        开始新的播放录音
        recordTimer = new Timer();
        TimerTask timerTask = new TimerTask() {
            @Override
            public void run() {
                runOnUiThread(() -> textView.getBackground().setLevel(textView.getBackground().getLevel() == 2 ? 1 : 2));
            }
        };
        recordTimer.schedule(timerTask, 0, 500);
        try {
            mediaPlayer = new MediaPlayer();
            mediaPlayer.setOnCompletionListener(mediaPlayer -> {
                if (recordTimer != null) {
                    recordTimer.cancel();
                }
            });
            try {
                mediaPlayer.setDataSource(filePath);
                if (!mediaPlayer.isPlaying()) {
                    mediaPlayer.prepare();
                    mediaPlayer.start();
                }
            } catch (IOException e) {
                mediaPlayer = null;
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
